<script setup lang="ts">
import { getEntity } from '@/api/develop/entity'
import { reactive, onBeforeMount, watch } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { useLocaleStore } from '@/store/modules/locale'
import { propTypes } from '@/utils/propTypes'
const emit = defineEmits(['nodeCheck'])
const { t } = useI18n()
const localeStore = useLocaleStore()
const MAIN_TABLE_ALIAS = 'main'

const props = defineProps({
  entId: propTypes.string, //主实体ID,
  initSelected: propTypes.array //初始选中字段
})

const state = reactive({
  treeData: [{} as any],
  curIds: '',
  title: t('dataList.chooseCol'),
  treeProps: {
    children: 'children',
    label: 'showName'
  },
  aliasIndex: {} as any
})

onBeforeMount(() => {
  const curLang = localeStore.getCurrentLocale.lang
  if (curLang == 'en') {
    state.treeProps.label = 'enName'
  } else if (curLang == 'zh_HK') {
    state.treeProps.label = 'hkName'
  }
})

//监控实体ID的变化
watch(
  () => props.entId,
  (val: string) => {
    if (!val) {
      state.treeData = []
      return
    }
    loadEntityData(val)
  },
  {
    immediate: true
  }
)

//加载实体对象
const loadEntityData = async (entId: string) => {
  const data = (await getEntity(entId)).data as any
  state.treeData = []
  if (!data) {
    return
  }
  let entity = {
    showName: data.entName,
    hkName: data.hkName,
    enName: data.enName,
    children: data.cols,
    tableName: data.tableName,
    tableAlias: MAIN_TABLE_ALIAS,
    colId: data.tableName,
    isEntity: true
  }
  state.treeData.push(entity)
  setChildrenAlias(entity)
}

//树节点选择事件
const handleNodeCheck = (node, checked) => {
  state.curIds = node.colId

  //只处理叶子节点
  if (node.children?.length > 0) {
    return
  }
  if (node.refEntId) {
    loadRefEntity(node)
    return
  }
  emit('nodeCheck', node, checked)
}

const setChildrenAlias = (node) => {
  const children = node.children
  const alias = node.tableAlias
  if (!children || children.length == 0) {
    return
  }
  for (const child of children) {
    child.tableAlias = alias
    if (child.refEntId) {
      child.showName += '❄'
      child.enName += '❄'
      child.hkName += '❄'
    }
    if (alias != MAIN_TABLE_ALIAS) {
      child.leftFieldName = node.fieldName
      child.leftTableAlias = node.leftTableAlias
      child.tableName = node.tableName
    }
  }
}

//加载引用实体的字段
const loadRefEntity = async (node) => {
  let refEntId = node.refEntId
  if (!refEntId) {
    return
  }
  const data = (await getEntity(refEntId)).data as any
  node.children = data.cols
  const tableName = data.tableName
  node.tableName = tableName
  node.leftTableAlias = node.tableAlias
  node.isEntity = true
  //取当前实体别名的索引（防止一个表被关联多次，别名重复）
  const index = getTableIndex(tableName)
  node.tableAlias = tableName + '_' + index
  node.colId = node.tableAlias
  setChildrenAlias(node)
}

//获取表别名索引
const getTableIndex = (tableName) => {
  let index = state.aliasIndex[tableName]
  if (!index) {
    //没有加载过的实体，默认别名后缀从1开始
    index = 0
  }
  index++
  state.aliasIndex[tableName] = index
  return index
}
</script>
<template>
  <div class="treeDiv">
    <div class="treeTitle" :title="$t('dataList.selectColTip')">{{ state.title }}</div>
    <el-tree
      :data="state.treeData"
      :props="state.treeProps"
      node-key="colId"
      show-checkbox
      default-expand-all
      highlight-current
      check-on-click-node
      :default-checked-keys="props.initSelected"
      :empty-text="$t('dataList.chooseEntity')"
      @check-change="handleNodeCheck"
      class="treeObject"
    />
  </div>
</template>

<style scoped>
.treeTitle {
  text-align: center;
  letter-spacing: 2px;
  line-height: 25px;
  font-size: 13px;
  background-color: #eee;
  color: #666;
}
.treeDiv {
  min-height: 400px;
  margin-top: 8px;
  width: 100%;
  border: 1px solid #ddd;
  background-color: white;
  overflow-y: auto;
}
.treeObject {
  width: 100%;
}
:deep(.el-tree-node__label) {
  font-size: 12px;
}
</style>
